// @flow
// 此页面在业务数据中点击客户编号跳转过来使用，跟某台设备不再有关系
import React from 'react'
import styles from './Customer.css'
import { Col, Row, Tabs } from 'antd'
import Line from 'components/Line'
import CustomerLi from 'components/CustomerLi'
import CustomerForm from 'components/CustomerForm'
import GotoCustomer from 'components/GotoCustomer'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import moment from 'moment'
import AgGrid from 'components/AgGrid'
import { saveDeviceData } from 'store/modules/deviceCard'
import { connect } from 'react-redux'
// import R from 'ramda'
// const FormItem = Form.Item
const TabPane = Tabs.TabPane

function callback (key) {
  // console.log(key)
}
const customerDefs = [
  { headerName: '事件名称',
    field: 'eventName',
    suppressMenu: true,
    cellStyle: {
      'padding': '8px'
    }
  },
  { headerName: '事件类型',
    field: 'eventType',
    suppressMenu: true,
    cellStyle: {
      'padding': '8px'
    }
  },
  { headerName: '开始时间',
    field: 'startTime',
    suppressMenu: true,
    cellRenderer: (params) => {
      return moment.unix(params.data.startTime).format('YYYY-MM-DD HH:mm:ss')
    },
    cellStyle: {
      'padding': '8px',
      'text-align':'center'
    }
  },
  { headerName: '结束时间',
    field: 'endTime',
    suppressMenu: true,
    cellRenderer: (params) => {
      return moment.unix(params.data.endTime).format('YYYY-MM-DD HH:mm:ss')
    },
    cellStyle: {
      'padding': '8px',
      'text-align':'center'
    }
  },
  { headerName: '处理方法',
    field: 'dealMethod',
    suppressMenu: true,
    cellStyle: {
      'padding': '8px'
    }
  },
  { headerName: '事件描述',
    field: 'detail',
    suppressMenu: true,
    cellStyle: {
      'padding': '8px'
    }
  }
]

type Props = {
  history: Object,
  saveDeviceData: Function
}

type States = {
  customerTypeData: Array<Object>,
  customer: Object,
  customerFields: Object,
  deviceData: Array<Object>,
  custormerData: Array<Object>,
  customerId: any,
  deviceDefs: Array<Object>
}
class Customer extends React.Component {
  props: Props
  state: States
  getCustomer: Function
  getCustomerType: Function
  getDevice: Function
  getCustomerGrid: Function
  goToDeviceCustomer: Function
  constructor (props: Props) {
    super(props)
    const component = this
    this.state = {
      customerTypeData: [],
      deviceDefs : [
        { headerName: '设备编号',
          field: 'deviceNo',
          width: 120,
          suppressMenu: true,
          cellStyle: {
            'padding': '8px'
          },
          cellRendererParams: {
            goToDeviceCustomer: component.goToDeviceCustomer.bind(this)
          },
          cellRendererFramework: GotoCustomer
        },
        { headerName: '设备名称',
          field: 'name',
          width: 150,
          suppressMenu: true,
          cellStyle: {
            'padding': '8px'
          }
        },
        { headerName: '设备类型',
          field: 'type',
          width: 150,
          suppressMenu: true,
          cellStyle: {
            'padding': '8px'
          }
        },
        { headerName: '设备型号',
          field: 'pinCode',
          width: 150,
          suppressMenu: true,
          cellStyle: {
            'padding': '8px' }
        },
        { headerName: '负责人',
          field: 'owner',
          width: 150,
          suppressMenu: true,
          cellStyle: {
            'padding': '8px'
          }
        },
        { headerName: '设备状态',
          field: 'status',
          width: 150,
          suppressMenu: true,
          cellStyle: {
            'padding': '8px'
          }
        },
        { headerName: '投运日期',
          field: 'operationDate',
          width: 180,
          suppressMenu: true,
          cellRenderer: (params) => {
            return moment(params.data.startTime).format('YYYY-MM-DD HH:mm:ss')
          },
          cellStyle: {
            'padding': '8px',
            'text-align':'center'
          }
        },
        { headerName: '生产日期',
          field: 'produceDate',
          width: 180,
          suppressMenu: true,
          cellRenderer: (params) => {
            return moment(params.data.startTime).format('YYYY-MM-DD HH:mm:ss')
          },
          cellStyle: {
            'padding': '8px',
            'text-align':'center'
          }
        },
        { headerName: '最后维修时间',
          field: 'latestRepairDate',
          width: 180,
          suppressMenu: true,
          cellRenderer: (params) => {
            return moment(params.data.endTime).format('YYYY-MM-DD HH:mm:ss')
          },
          cellStyle: {
            'padding': '8px',
            'text-align':'center'
          }
        }
      ],
      customer: {},
      customerFields: {},
      deviceData:[],
      custormerData:[],
      customerId:''
    }
    this.getCustomer = this.getCustomer.bind(this)
    this.getCustomerType = this.getCustomerType.bind(this)
    this.getCustomerGrid = this.getCustomerGrid.bind(this)
    this.getDevice = this.getDevice.bind(this)
    this.goToDeviceCustomer = this.goToDeviceCustomer.bind(this)
  }
  componentWillReceiveProps (nextProps: Props) {
    this.getCustomer(nextProps)
  }
  componentWillMount () {
    this.getCustomer(this.props)
  }
  getCustomerType () {
    const { customerId } = this.state
    const component = this
    universalFetch(`${__SERVICE_API__}device/events/customers/types/count?customer_id=${customerId}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        component.setState({
          customerTypeData: [{
            type: 'pie',
            name: '数量',
            data: json.result.map((d, i) => {
              return [d.eventType, d.count]
            })
          }]
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getDevice () {
    const { customerId } = this.state
    const component = this
    universalFetch(`${__SERVICE_API__}device/customers/${customerId}/devices`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        component.setState({
          deviceData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  goToDeviceCustomer (data: Object) {
    const { history, saveDeviceData } = this.props
    saveDeviceData(data)
    history.push(`/device-file/${data.id}/overview`)
  }
  getCustomerGrid () {
    const { customerId } = this.state
    const component = this
    universalFetch(`${__SERVICE_API__}device/customers/${customerId}/events`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        component.setState({
          custormerData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getCustomer (props: Object) {
    const { history } = props
    const { data } = history.location.state
    const result = data
    let city = result.region.city
    if (city === '市辖区') {
      city = ''
    }
    const name = result.region.province + city + result.region.district
    this.setState({
      customerId: result.id,
      customer: result,
      customerFields: {
        '客户名称': result.name,
        '客户编号': result.customerNo,
        '客户行业': result.industry,
        '机组状态': result.priorStatus,
        '机组数量': result.count,
        '客户地址': name,
        // '经度': result.region.longitude,
        // '纬度': result.region.latitude,
        '在线机组数量': result.onlineCount,
        '客户类型': result.type
      }
    }, () => {
      this.getCustomerType()
      this.getDevice()
      this.getCustomerGrid()
    })
  }
  render () {
    const { deviceDefs, customerFields, deviceData, custormerData, customerId, customerTypeData } = this.state
    return (
      <div className={styles['main']}>
        <div className={styles['top']}>
          <Row gutter={20}>
            <Col span='12'>
              <CustomerLi title='客户信息' data={customerFields} />
            </Col>
            <Col span='12'>
              <div className={styles['pie']}>
                <Line chartData={customerTypeData} title='客户事件统计图' />
              </div>
            </Col>
          </Row>
        </div>
        <Tabs onChange={callback} type='card' style={{ marginTop:20 }}>
          <TabPane tab='设备列表' key='1'>
            <div className={styles['tabCon']}>
              <AgGrid columnDefs={deviceDefs} rowData={deviceData} />
            </div>
          </TabPane>
          <TabPane tab='客户事件列表'key='2'>
            <div className={styles['tabCon']}>
              <AgGrid columnDefs={customerDefs} rowData={custormerData} />
            </div>
          </TabPane>
          <TabPane tab='添加客户事件' key='3'>
            <CustomerForm customerId={customerId} onChange={this.getCustomerGrid} />
          </TabPane>
        </Tabs>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  const { deviceCard } = state
  return {
    groupId: deviceCard.groupId
    // deviceId: deviceCard.deviceData.id
  }
}
export default connect(mapStatesToProps, { saveDeviceData })(Customer)
